
package rmTags;

use strict;

sub rmOnce {
    my $string = shift || '';
    my $tag = shift || '';
    my $k = shift || 0;
    
    return {'s' => $string, 'k' => 0} unless ($tag);
    
    if ($string =~ /<$tag/i) {
	$string =~ s/<$tag//i;
	$k++;
    } elsif ($string =~ /<\/$tag/i) {
	$string =~ s/<\/$tag//i;
	$k--;
    }
    return {'s' => $string, 'k'=> $k};
}

sub rmAll {
    my $string = shift || '';
    my $tag = shift || '';
    
    return {'s' => $string, 'k' => 0} unless ($tag);
    
    my ($k, $kk) = (0, 0);
    do {
	$kk = $k;
	
	my $res = rmTags::rmOnce($string, $tag, $k);
	$string = $res->{'s'};
	$k     = $res->{'k'};
	
    } while ($k > 0 && ($k != $kk));
    
    return {'s' => $string, 'k' => $k};
}

sub rmByClass {
    my $sarr_ = shift || [];
    my $tag = shift || '';
    my $class = shift || '';
    
    my @out = ();
    my @sarr = @{$sarr_};
    
    return {'s' => '', 'k' => 0} unless ($tag && $class);
    
    my ($f, $s) = (0, '');
    
    for (my $i=0; $i<=$#sarr; ++$i) {
	if (!$f) {
	    if ($sarr[$i] =~ /<$tag\s[^>]*?class=["'][^"']*$class[ "']/i) { #"'
		$f = 1;
		$s = $sarr[$i];
		$s =~ s/<$tag\s[^>]*?class=["'][^"']*$class[ "'].*$//i; #"'
		push @out, $s;
		$s = $sarr[$i];
		$s =~ s/^.*?(<$tag\s[^>]*?class=["'][^"']*$class[ "'].*)$/$1/i; #"'
	    } else {
		push @out, $sarr[$i];
		next;
	    }
	} else {
	    $s   .= $sarr[$i];
	}
	
	#rm tags block
	{
	    my $res = rmTags::rmAll($s, $tag);
	    if ($res->{'k'} == 0) {
		$f = 0;
		$s =~ s/<$tag.*<\/$tag>//gs;
		push @out, $s;
	    }
	}
    }

    if ($f) {
	$s =~ s/<$tag\s.*<\/$tag>//gs;
	push @out, $s;
    }

    return \@out;
}

1;